import json
import sys
from PySide2.QtCore import Qt
from PySide2.QtGui import QStandardItemModel, QStandardItem, QIcon
from PySide2.QtWidgets import QApplication, QMainWindow, QTreeView, QWidget, QVBoxLayout
from dayu_widgets import MTreeView

from test2.split.plugin_search import PluginSearch


class PluginView(QWidget):
    def __init__(self, parent=None):
        super(PluginView, self).__init__(parent)
        self.initUI()

    def initUI(self):
        # 创建树形视图并设置模型
        self.treeview = MTreeView(self)
        self.set_tree_view()
        self.treeview.setColumnWidth(0, 300)

        # 设置树形视图选项
        self.treeview.setAnimated(True)  # 启用动画效果
        self.treeview.setHeaderHidden(True)  # 隐藏表头
        plugin_search = PluginSearch(self.treeview)
        plugin_search.update_tree_view_signal.connect(self.set_tree_view)
        plugin_search.expend_tree_view_signal.connect(self.expend_tree_view)

        main_lay = QVBoxLayout()
        main_lay.addWidget(plugin_search)
        main_lay.addWidget(self.treeview, 1)
        self.setLayout(main_lay)

    def expend_tree_view(self, key):
        if key == "OPEN":
            self.treeview.expandAll()
        else:
            self.treeview.collapseAll()

    def set_tree_view(self, search_text=None):
        print("search_text = {}".format(search_text))
        with open("./doc/plugin.json", "r", encoding="utf-8") as f:
            plugin_json_array = json.load(f)
        # 创建模型并添加数据
        model = QStandardItemModel()

        for plugin_dir_obj in plugin_json_array:
            name = plugin_dir_obj["name"]
            type = plugin_dir_obj["type"]
            plugins = plugin_dir_obj["plugins"]
            parent_item = QStandardItem(name)
            parent_item.setIcon(QIcon('./doc/folder.png'))
            parent_item.setEditable(False)
            for plugin in plugins:
                plugin_name = plugin["name"]
                if search_text is None or search_text in plugin_name:
                    plugin_icon = plugin["icon"]
                    child_item = QStandardItem(plugin_name)
                    if plugin_icon == "default":
                        child_item.setIcon(QIcon('./doc/file.png'))
                        child_item.setEditable(False)
                    parent_item.appendRow(child_item)
            model.appendRow(parent_item)
        self.treeview.setModel(model)
        self.treeview.expandAll()


if __name__ == "__main__":
    # Import local modules
    from dayu_widgets import dayu_theme
    from dayu_widgets.qt import application

    with application() as app:
        test = PluginView()
        dayu_theme.apply(test)
        test.show()
